const express = require('express');
const fs = require('fs').promises;
const path = require('path');

const app = express();
const port = 3002;

// 静态文件中间件
app.use(express.static('public'));

// 搜索API接口
app.get('/api/search', async (req, res) => {
  // 记录IP地址到文件
  const ip = req.ip; // 获取客户端IP
  const timestamp = new Date().toISOString();
  const logLine = `${timestamp} - ${ip}\n`;
  const ipLogPath = path.join(__dirname, 'ip_log.txt');
  
  // 异步写入日志，捕获错误但不阻塞后续处理
  fs.appendFile(ipLogPath, logLine).catch(err => {
    console.error('无法记录IP地址:', err);
  });

  try {
    const query = req.query.q.toLowerCase();
    const dataPath = path.join(__dirname, 'data.json');
    const rawData = await fs.readFile(dataPath, 'utf-8');
    const items = JSON.parse(rawData);
    
    const results = items.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.content.toLowerCase().includes(query)
    );
    
    res.json(results);
  } catch (error) {
    res.status(500).json({ error: '服务器错误' });
  }
});

app.listen(port, () => {
  console.log(`服务器运行在 http://127.0.0.1:${port}`);
});